import { Toast, NavBar, Form, Input, Uploader, Button, Switch } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import axios from 'axios';
import { useEffect, useState } from 'react';
import { addComplaint } from '../../interfaces';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
export default function Complaint() {
    let name = localStorage.getItem('name')
    let user = localStorage.getItem('user')

    let navigate = useNavigate();
    const [defaultValue, setdefaultValue] = useState([]);
    const [videoFiles, setVideoFiles] = useState([]);
    const [form] = Form.useForm();
    const [check, setcheck] = useState(true);
    const {
        transcript,
        listening,
        resetTranscript,
        browserSupportsSpeechRecognition,
        isMicrophoneAvailable
    } = useSpeechRecognition();
    useEffect(() => {
        if (transcript) {
            form.setFieldsValue({
                content: form.getFieldValue('content') + transcript,
            });
        }


    }, [transcript])
    // 检查浏览器是否支持
    if (!browserSupportsSpeechRecognition) {
        return <div>您的浏览器不支持语音识别功能</div>;
    }
    // 检查麦克风是否可用
    if (!isMicrophoneAvailable) {
        return <div>无法访问麦克风，请检查权限设置</div>;
    }


    const startListening = () => {
        SpeechRecognition.startListening({
            language: 'zh-CN', // 设置中文识别
            continuous: true   // 持续识别（默认为false，识别一句话后自动停止）
        });
    };
    console.log(transcript);
    const shut = () => {
        SpeechRecognition.stopListening();
        resetTranscript();


    }

    const handleupload = async (file) => {
        console.log(file);
        const formData = new FormData();
        formData.append('file', file);
        console.log(formData);

        let { data: { path } } = await axios.post('http://localhost:3009/upload', formData);
        console.log(path); // path返回的图片路径
        setdefaultValue([...defaultValue, { url: path }]);
        return { url: path };
    };
    // 处理视频上传
    // 修改handleVideoUpload函数
    const handleVideoUpload = async (file) => {

        // 检查文件类型
        if (!file.type.includes('video/')) {
            Toast.fail('请上传视频文件');
            return Promise.reject('Invalid file type');
        }
        const formData = new FormData();
        formData.append('file', file);

        try {
            let { data: { path } } = await axios.post('http://localhost:3009/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            setVideoFiles([...videoFiles, { url: path }]);
            return { url: path };
        } catch (error) {
            Toast.fail('视频上传失败');
            return Promise.reject(error);
        }
    };


    const onFinish = async (values) => {
        console.log('表单提交数据:', values);
        let a = dayjs().format('YYYY-MM-DD HH:mm:ss')
        await addComplaint({ ...values, time: a, name: check ? '匿名' : user, school: name, user: user })
        Toast.success('投诉成功')
        form.resetFields()
        setdefaultValue([])
    };
    return (
        <div style={{ backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
            <NavBar onClickLeft={() => { navigate(-1) }} title="投诉举报" style={{ '--rv-nav-bar-arrow-size': '20px', '--rv-nav-bar-icon-color': 'red' }} />
            <Form
                initialValues={{ type: '食品安全' }}
                form={form}
                onFinish={onFinish}
                style={{
                    backgroundColor: 'white',
                    padding: '16px',
                    margin: '16px',
                    borderRadius: '12px'
                }}
                footer={
                    <div style={{ margin: '16px 0', padding: '0 16px' }}>
                        <Button
                            round
                            nativeType='submit'
                            type='primary'
                            block
                            style={{
                                height: '44px',
                                fontSize: '16px',
                                fontWeight: 'bold',
                                backgroundColor: '#07C160',
                                border: 'none'
                            }}
                        >
                            发布
                        </Button>
                    </div>
                }
            >
                <Form.Item
                    name="title"
                    label="投诉标题"
                    labelAlign="top"
                    style={{
                        marginBottom: '24px',
                        borderBottom: '1px solid #f0f0f0',
                        paddingBottom: '12px'
                    }}
                    rules={[{ required: true, message: '请填写投诉标题' }]}
                >
                    <Input
                        placeholder="请输入"
                        style={{
                            backgroundColor: 'transparent',
                            border: 'none',
                            padding: '0',
                            fontSize: '14px'
                        }}
                    />
                </Form.Item>
                <Form.Item
                    name="type"
                    label="选择类型"
                    labelAlign="top"
                    rules={[{ required: true, message: '请选择类型' }]}
                    style={{
                        marginBottom: '24px',
                        borderBottom: '1px solid #f0f0f0',
                        paddingBottom: '12px'
                    }}
                >
                    <select
                        style={{
                            width: '100%',
                            padding: '0',
                            backgroundColor: 'transparent',
                            border: 'none',
                            outline: 'none',
                            fontSize: '14px',
                            color: '#333',
                            appearance: 'none'
                        }}
                    >
                        <option value="食品安全">食品安全</option>
                        <option value="卫生安全">卫生安全</option>
                        <option value="其它">其它</option>
                    </select>
                </Form.Item>

                {/* 投诉内容 */}
                <Form.Item
                    name="content"
                    label={<div><p>投诉内容</p>
                        <p>{listening ? '正在...' : '语音转文字'} </p>
                        <Button color='#07C160' round style={{ width: '80px', fontSize: '10px', height: '20px' }} onClick={startListening} disabled={listening} >  开始录音</Button>
                        <Button color='#07C160' round style={{ width: '80px', fontSize: '10px', height: '20px' }} onClick={shut} disabled={!listening}>  停止录音</Button>
                    </div>}
                    labelAlign="top"
                    rules={[{ required: true, message: '请填写投诉内容' }]}
                    style={{
                        marginBottom: '24px',
                        borderBottom: '1px solid #f0f0f0',
                        paddingBottom: '12px'
                    }}
                >
                    <Input.TextArea
                        rows={3}
                        autoSize
                        maxLength={200}
                        showWordLimit

                        clearable
                        placeholder="投诉的发布要填写的内容，最多200字"
                        style={{
                            backgroundColor: 'transparent',
                            border: 'none',
                            padding: '0',
                            fontSize: '14px',
                            '--rv-textarea-word-limit-color': '#999'
                        }}
                    />
                </Form.Item>

                {/* 相关图片 */}
                <Form.Item
                    name="images"
                    label="相关照片"
                    labelAlign="top"
                    style={{
                        marginBottom: '24px',
                        borderBottom: '1px solid #f0f0f0',
                        paddingBottom: '12px'
                    }}
                >
                    <Uploader
                        accept="*"
                        defaultValue={defaultValue}
                        upload={handleupload}
                        style={{
                            '--rv-uploader-upload-background-color': 'transparent',
                            '--rv-uploader-upload-border': '1px dashed #ddd'

                        }}
                    />
                </Form.Item>

                <Form.Item
                    name="videos"
                    label="相关视频"
                    labelAlign="top"
                >
                    <Uploader
                        accept="video/*"
                        value={videoFiles}
                        onChange={setVideoFiles}
                        upload={handleVideoUpload}
                        multiple={true}
                        capture="camcorder"
                        previewCoverRender={(file, actions) => (
                            <div style={{
                                width: '100px',
                                height: '200px',
                                position: 'relative',
                                margin: '8px 20px',
                                border: '1px solid #eee',
                                borderRadius: 8,
                            }}>
                                <video
                                    controls
                                    src={file.url}
                                    style={{
                                        width: '100px',
                                        maxHeight: '150px',
                                        borderRadius: 8,
                                        backgroundColor: '#000'
                                    }}
                                />
                            </div>
                        )}
                    />
                </Form.Item>




                <Form.Item
                    name="anonymous"
                    labelAlign="top"
                    style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        marginBottom: '24px',
                        borderBottom: '1px solid #f0f0f0',
                        paddingBottom: '12px'
                    }}
                >
                    <span style={{
                        fontSize: '16px',
                        color: '#333',
                        fontWeight: 'bold'
                    }}>匿名</span>
                    <Switch
                        size="24px"
                        activeColor="#07C160"
                        inactiveColor="#dcdee0"
                        checked={check}
                        onChange={() => setcheck(!check)}
                    />
                </Form.Item>
            </Form>
        </div>
    );
}